package com.yonyou.pmclouds.alterandvisa.rmiimpl;


import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.alterandvisa.entity.AlterAndVisaListViewVO;
import com.yonyou.pmclouds.alterandvisa.entity.AlterAndVisaVO;
import com.yonyou.pmclouds.alterandvisa.entity.VisaDemoVO;
import com.yonyou.pmclouds.alterandvisa.mapper.AlterAndVisaMapper;
import com.yonyou.pmclouds.alterandvisa.rmiitf.AlterAndVisaQuery;
import com.yonyou.pmclouds.alterandvisacategory.rmiitf.AlterAndVisaCategoryQuery;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.pmpub.entity.QueryListParam;
import com.yonyou.pmclouds.pmpub.rmiitf.IPageQuerySerivce;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.projectpart.service.IProjectpartQryService;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.entity.TeamMemberVO;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseQuery;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service(version = ApplicationConsts.APPLICATION_VERSION,interfaceClass= AlterAndVisaQuery.class)
public class AlterAndVisaQueryImpl implements AlterAndVisaQuery, IPageQuerySerivce<AlterAndVisaVO> {

    @Autowired
    private AlterAndVisaMapper mapper;
    @Autowired
    private PictureRemoteService picService;
    @Autowired
    private ProjectSimpleQuery projectQuery;
    @Autowired
    private TeamMemberQuery teamMemberQuery;
    @Autowired
    private TeamEnterpriseQuery teamEnterpriseQuery;
    @Autowired
    private AlterAndVisaCategoryQuery alterAndVisaCategoryQuery;
    @Autowired
    private OrganizationQuery organizationQuery;
    @Autowired
    private IProjectpartQryService projectpartQryService;

    @Override
    public AlterAndVisaListViewVO[] getAlterAndVisaListInfo(String pkProject) throws BusinessException {
        if(StringUtils.isEmpty(pkProject)){
            return null;
        }
        AlterAndVisaListViewVO[] result = mapper.getListViewVOByProject(pkProject);
        if(ArrayUtils.isEmpty(result)){
            return new AlterAndVisaListViewVO[0];
        }
        List<String> keys = new ArrayList<>();
        for(AlterAndVisaListViewVO vo : result){
            if(vo != null && StringUtils.isNotEmpty(vo.getPkAlterandvisa())){
                keys.add(vo.getPkAlterandvisa());
            }
        }
        setCategoryInfoForView(result);//类别参照信息
        getPictures(result);
        return result;
    }

    @Override
    public AlterAndVisaVO getById(String pkAlterandvisa) throws BusinessException {
        if(StringUtils.isEmpty(pkAlterandvisa)){
            return null;
        }
        String[] pics = picService.queryPicNamesByPkEntity(pkAlterandvisa);  //查询图片
        AlterAndVisaVO result = mapper.getById(pkAlterandvisa);
        if(result != null){
            result.setPictures(pics);
        }
        setRefInfo(result);   //项目参照信息
        setCategoryInfo(result);//类别参照信息
        projectpartQryService.fillProjectpartName(result);//工程部位参照信息
        return result;
    }


    @Override
    public boolean queryRefByIds(String code, String[] ids) throws BusinessException {
        if(StringUtils.isEmpty(code) || ArrayUtils.isEmpty(ids)){
            return false;
        }
        return mapper.getRefByIds(code, SqlUtil.getSqlIn(ids)) > 0;
    }

    @Override
    public VisaDemoVO getVisaDemo(String pkTenant, String pkUser, String inputProject) throws BusinessException {
        VisaDemoVO result = new VisaDemoVO();
        // 模糊匹配项目
        List<ProjectVO> projectVOs = projectQuery.queryProjectsByFuzzyName(inputProject, pkTenant);
        // 判断是否匹配到项目
        if (projectVOs == null || projectVOs.size() == 0) {
            List<TeamMemberVO> teamMemberVOs = teamMemberQuery.queryByUserAndTenant(pkUser, pkTenant);
            if (teamMemberVOs != null && teamMemberVOs.size() > 0) {
                TeamMemberVO teamMemberVO = teamMemberVOs.get(0);
                String project = teamMemberVO.getPkProject();
                result.setPkProject(project);
                List<TeamEnterpriseVO> enterpriseVOs = teamEnterpriseQuery.queryConstructEnterByProject(project, pkTenant);
                if (enterpriseVOs != null && enterpriseVOs.size() > 0) {
                    result.setPkConstructEnterprise(enterpriseVOs.get(0).getPkEnterprise());
                }
                ProjectVO currProject = projectQuery.queryProject(teamMemberVO.getPkProject());
                result.setProjectName(currProject.getSname());
                result.setProjectCode(currProject.getScode());
                result.setPkTenant(currProject.getPkTenant());
            }
        } else {
            ProjectVO projectVO = projectVOs.get(0);
            result.setPkProject(projectVO.getPkProject());
            result.setProjectName(projectVO.getSname());
            result.setProjectCode(projectVO.getScode());
            result.setPkTenant(projectVO.getPkTenant());
            List<TeamEnterpriseVO> teamEnterpriseVOs = teamEnterpriseQuery.queryConstructEnterByProject(projectVO.getPkProject(), pkTenant);
            if (teamEnterpriseVOs != null && teamEnterpriseVOs.size() > 0) {
                result.setPkConstructEnterprise(teamEnterpriseVOs.get(0).getPkEnterprise());
            }
        }
        return result;
    }

    @Override
    public PageObject<Object> queryByCondition(String[] pkProjects, String[] creators, String startDate, String endDate, int[] billStatus, int pageStart, int pageSize) throws BusinessException {

        int count = mapper.countByCondition(null, pkProjects, creators, startDate, endDate, billStatus);
        AlterAndVisaVO[] alterAndVisaVOs = mapper.queryByCondition(pkProjects, creators, startDate, endDate, billStatus, pageStart, pageSize);

        return new PageObject<Object>(setRefFiledInfo(alterAndVisaVOs),count,pageStart);
    }

    @Override
    public int countByCondition(String pkTenant, String[] pkProjects, String[] creators, String startDate, String endDate, int[] billStatus) throws BusinessException {
        return mapper.countByCondition(pkTenant, pkProjects, creators, startDate, endDate, billStatus);
    }

    /**
     * 添加照片
     */
    private void getPictures(AlterAndVisaListViewVO[] vos) throws BusinessException {
        if(ArrayUtils.isEmpty(vos)) return;
        List<String> pkBills = new ArrayList<>();
        for(AlterAndVisaListViewVO vo : vos){
            if(vo != null && vo.getPkAlterandvisa() != null) pkBills.add(vo.getPkAlterandvisa());
        }
        if(pkBills.size() == 0) return;

        Map<String, List<String> > picMap = picService.queryPicsByPkEntitys(pkBills.toArray(new String[0]));
        if(picMap == null) return;

        for(AlterAndVisaListViewVO vo : vos){
            if(vo != null && picMap.get(vo.getPkAlterandvisa()) != null){
                vo.setPictures(picMap.get(vo.getPkAlterandvisa()).toArray(new String[0]));
            }
        }
    }


    private void setRefInfo(AlterAndVisaVO vo) throws BusinessException {
        // 项目
        ProjectVO projectVO = projectQuery.queryProject(vo.getPk_project());
        vo.setProjectName(projectVO.getSname());
        vo.setProjectCode(projectVO.getScode());

        String pkOrg = projectVO.getPkOrg();
        if(StringUtils.isNotEmpty(pkOrg)) {
            OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), pkOrg);
            vo.setOrgName(organizationVO==null?null:organizationVO.getSname());
        }
    }

    private void setCategoryInfoForView(AlterAndVisaListViewVO[] vos) throws BusinessException {
        //签证类别
        String[] ids = null;
        for(AlterAndVisaListViewVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltervisacategory())){
                ids = ArrayUtils.add(ids, vo.getPkAltervisacategory());
            }
        }
        //获取主键名字映射
        Map<String, String> categoryMap = alterAndVisaCategoryQuery.queryNameByIds(ids);
        for(AlterAndVisaListViewVO vo : vos){
            if(StringUtils.isNotBlank(vo.getPkAltervisacategory())){
                vo.setCategoryName(categoryMap.get(vo.getPkAltervisacategory()));
            }
        }
    }

    private void setCategoryInfo(AlterAndVisaVO vo) throws BusinessException {
        if(StringUtils.isNotBlank(vo.getPkAltervisacategory())){
            //签证类别
            Map<String, String> categoryMap = alterAndVisaCategoryQuery.queryNameByIds(new String[]{vo.getPkAltervisacategory()});
            vo.setCategoryName(categoryMap.get(vo.getPkAltervisacategory()));
        }
    }


    /**
     * 处理参照字段，非必输项需校验空
     *
     * @param vos
     * @return
     * @throws BusinessException
     */
    private AlterAndVisaVO[] setRefFiledInfo(AlterAndVisaVO[] vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return new AlterAndVisaVO[0];
        }

        Set<String> categorySet = new HashSet<String>();
        Set<String> projectSet = new HashSet<String>();
        Set<String> pkSet = new HashSet<String>();

        for (AlterAndVisaVO vo:
                vos) {
            categorySet.add(vo.getPkAltervisacategory());
            projectSet.add(vo.getPk_project());
            pkSet.add(vo.getPkAlterandvisa());
        }

        Map<String,String>  categoryNameMap = alterAndVisaCategoryQuery.queryNameByIds(categorySet.toArray(new String[0]));
        Map<String,ProjectVO> projectVOMap = projectQuery.queryProjects(projectSet.toArray(new String[0]));
        Map<String,List<String>> picMap = picService.queryPicsByPkEntitys(pkSet.toArray(new String[0]));

        for (AlterAndVisaVO vo:
                vos) {
            vo.setProjectName(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getSname());
            vo.setProjectCode(projectVOMap.get(vo.getPk_project()) == null ? null:projectVOMap.get(vo.getPk_project()).getScode());
            vo.setCategoryName(categoryNameMap.get(vo.getPkAltervisacategory()));
            vo.setPicNum(picMap.get(vo.getPkAlterandvisa()) == null ? 0 : picMap.get(vo.getPkAlterandvisa()).size());
        }
        //填充工程部位名称
        projectpartQryService.fillProjectpartName(vos);
        return vos;
    }

    @Override
    public int countByProject(QueryListParam param) throws BusinessException{

        int count = mapper.countByCondition(null, new String[]{param.getPkProject()}, null, param.getStartDate(), param.getEndDate(), null);

        return count;
    }

    @Override
    public AlterAndVisaVO[] queryByProject(QueryListParam param) throws BusinessException {

        AlterAndVisaVO[] vos = mapper.queryByCondition(new String[]{param.getPkProject()}, null, param.getStartDate(), param.getEndDate(), null,param.getPageStart(),param.getPageSize());

        return setRefFiledInfo(vos);
    }

    @Override
    public String getBillType() {
        return BillTypeConst.ALTER_AND_VISA_BILLTYPE;
    }
}
